package me.yuzho.study.concurrency;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class Pair { // Not thread-safe
    
    private int x, y;
    
    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public Pair() {
        this(0, 0);
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
    
    public void increamentX() { x++; }
    public void increamentY() { y++; }

    @Override
    public String toString() {
        return String.format("X: %d, Y: %d", x, y);
    }
    
    public class PairValuesNotEqualException extends RuntimeException {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public PairValuesNotEqualException() {
            super("Pair values not equal : " + Pair.this);
        }
    }
    
    public void checkState() {
        if(x != y) {
            throw new PairValuesNotEqualException();
        }
    }
}


/** Protect a pair inside a thread-safe class
 * @author yzhou-citrix
 *
 */
abstract class PairManager {
    AtomicInteger checkCounter = new AtomicInteger(0);
    protected Pair p = new Pair();
    
    private List<Pair> storage = Collections.synchronizedList(new ArrayList<Pair>());
    
    public synchronized Pair getPair() {
        
        return new Pair(p.getX(), p.getY());
    }
    
    // Assume this is a time consuming operation
    protected void store(Pair p) {
        storage.add(p);
        
        try {
            TimeUnit.MILLISECONDS.sleep(50);
        } catch (InterruptedException e) {
            //e.printStackTrace();
        }
    }
    
    public abstract void increment();
}


// synchronize the entire method
class PairManager1 extends PairManager {

    @Override
    public synchronized void increment() {
        p.increamentX();
        p.increamentY();
        store(p);
    }
    
}

// use a critical section
class PairManager2 extends PairManager {

    @Override
    public void increment() {
        
        Pair temp;
        synchronized (this) {
            p.increamentX();
            p.increamentY();
            temp = getPair();         
        }
        
        store(temp); 
    } 
}

class PairManipulator implements Runnable {
    private PairManager pm;
    
    public PairManipulator(PairManager pm) {
        this.pm = pm;
    }

    @Override
    public void run() {
        while(true) {
            pm.increment();
        }
    }

    @Override
    public String toString() {
        return "Pair " + pm.getPair() + " checkCounter = " + pm.checkCounter.get();
    }
}


class PairChecker implements Runnable {

    private PairManager pm;
    
    public PairChecker(PairManager pm) {
        this.pm = pm;
    }
    
    @Override
    public void run() {
        while(true) {
            pm.checkCounter.incrementAndGet(); //累加检查次数
            pm.getPair().checkState(); //检查状态
        }
        
    }
    
}

public class CriticalSection {

    // Test the two different approaches
    public static void testApproaches(PairManager pman1, PairManager pman2) {
        ExecutorService exec = Executors.newCachedThreadPool();
        
        PairManipulator
            pm1 = new PairManipulator(pman1),
            pm2 = new PairManipulator(pman2);
        
        PairChecker
            pcheck1 = new PairChecker(pman1),
            pcheck2 = new PairChecker(pman2);
        
        exec.execute(pm1);
        exec.execute(pm2);
        exec.execute(pcheck1);
        exec.execute(pcheck2);
        exec.shutdown();
        
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("pm1: " + pm1 + ",\n pm2: " + pm2);
        System.exit(0);
    }
    
    public static void main(String[] args) {
        
        PairManager 
            pm1 = new PairManager1(),
            pm2 = new PairManager2();
            
         
        testApproaches(pm1, pm2);

    }

}
